import React, { Component, PropTypes } from 'react'
import _ from 'underscore'
import '../../../dist/css/modal-file.css'
import { merge, numberArray } from '../helper/helper'

export default class Table extends Component {
    componentDidMount() {
        this.sendRequst()
    }
    shouldComponentUpdate(nextProps, nextState) {
        const options = this.props.options;
        const trigger = options.trigger;
        var shouldTrigger = false;

        if (trigger && trigger.length) {
            trigger.forEach((i) => {
                if (this.props[i] !== nextProps[i]) {
                    shouldTrigger = true
                }
            });

            if (shouldTrigger) {
                setTimeout(() => this.sendRequst())
            }
        }
        return true
    }
    getQuery() {
        const { options, skip, orderBy, direction,currentPageIndex, targetPageIndex } = this.props;
        const trigger = options.trigger;
        let shouldSend = true,
            query = {
                currentPageIndex: currentPageIndex,
                targetPageIndex: targetPageIndex,
            };

        if (options.pagebar) {
            query.skip = skip;
            query.limit = options.limit
        }

        if (options.sorting) {
            query.orderBy = orderBy;
            query.direction = direction
        }
        if (trigger && trigger.length) {
            trigger.forEach((i) => {
                if (i != 'trigger') {
                    if (typeof this.props[i] == "undefined") {
                        shouldSend = false
                    }
                    query[i] = this.props[i];
                }
            })
        }
        return {
            query: query,
            shouldSend: shouldSend
        }
    }
    sendRequst(params) {
        const { getData, isPending } = this.props;
        if (!isPending) {
            let curQuery = this.getQuery();
            let query = merge(curQuery.query, params);
            let shouldSend = curQuery.shouldSend;
            if (shouldSend) {                
                getData(query)
            }
        }
    }
    render() {
        const { options, isPending, checked, placeholder } = this.props;
        const getQuery = this.getQuery.bind(this);
        const sendRequst = this.sendRequst.bind(this);

        // {
        //     checked && checked.length ? <div className="operate" style={{color: '#108ee9', float: 'left'}}><span style={{opacity: '.6'}}>已选择{checked.length}项</span> <span className="fa fa-trash fa-lg"></span><a href="javascript:void(0)">删除</a></div> : ''
        // }

        return <div className="box box-solid parllay-table">
            <div className="box-header with-border">
                {/* {
                    options.title ?
                        <h3 className="box-title">{options.title}</h3>
                        : ''
                } */}
                {options.download ? <DownLoad downloadUrl={options.downloadUrl} getQuery={getQuery} /> : null}
                {/* {options.setting ? <div className="btn-group pull-right" style={{ marginRight: options.download ? 10 : 0 }} >
                    <a type="button" href={options.setting} className="btn btn-default btn-sm" title="设置"><i className="fa fa-wrench text-muted"></i></a>
                </div> : null} */}
                {options.search ? <div className="btn-group pull-right search-goods" style={{ width: 250, marginRight: 10 }}><SearchBar onSubmit={sendRequst} placeholder={options.placeholder} thead={options.thead} theKey={options.search} val={this.props[options.search]} />
                    {/* <button>1111</button> */}
                </div> : null}
            </div>
            <TBody {...this.props} sendRequst={sendRequst} />
            {options.pagebar ? <TFoot {...this.props} sendRequst={sendRequst} /> : null}
            {isPending ? <div className="overlay" style={{ display: 'block' }}><i className="fa fa-refresh fa-spin"></i></div> : null}
        </div>
    }
}

class TBody extends Component {
    render() {
        const { data, options,sendRequst, checked, onCheck } = this.props;
        let chosen= [0,1,2,3,4,5,6,7,8] ////////////决定tobody有几个
        return <div className="box-body">
            <table className="table">
                <tbody>
                    <THead {...this.props} />
                    {data.length ?
                        data.map((i, index) => <Tr key={index} index={index} options={options} data={i} chosen={chosen} sendRequst={sendRequst} checked={checked} onCheck={onCheck} />) :
                        <tr><td colSpan={chosen.length} style={{ textAlign: 'center' }}></td></tr>
                    }
                </tbody>
            </table>
        </div>
    }
}

class THead extends Component {
    sorting(val) {
        console.log(val)
        const { options, orderBy, sendRequst, direction } = this.props;
    
        if (orderBy != val) {
            sendRequst({
                'orderBy': val,
                'direction': 'DESC',
                'skip': 0
            })
        } else {
            sendRequst({
                'direction': (direction == 'DESC' ? 'ASC' : 'DESC'),
                'skip': 0
            })
        }
    }
    render() {
        const self = this;
        const { options, chosen, orderBy, direction, checked, onCheck, data } = this.props;
        const limit = options.limit;
        if (onCheck) {
            var isChecked = checked.length == limit
        }

        return <tr>
            {onCheck && !options.only && data.length ? <th width={50}>
                <input type="checkbox" checked={isChecked} onChange={() => onCheck(isChecked ? [] : numberArray(0, limit))} />
            </th> : null}
            {
                options.only ? <th></th> : null
            }
            {chosen.map((i, index) => {
                const th = options.thead[i];
                const isSort = options.sorting && th.sort;
                const className = (isSort ? orderBy == th.sort ? direction == 'DESC' ? 'sorting_desc' : 'sorting_asc' : '' : '');
                return <th key={index} className={className} width={th.width || ''} onClick={options.sorting ? () => self.sorting(th.sort) : null}>{th.name}</th>
            })}
        </tr>
    }
}

class Tr extends Component {

    render() {
        const { options, index, chosen, sendRequst, checked, onCheck } = this.props;
        const limit = options.limit;
        let data = this.props.data;
        
        if (onCheck) {
            var isChecked = _.contains(checked, index);
        }
        
        if (options.beforeRender) {
            data = options.beforeRender(data, options) || data
        }
        return(
            <tr>
                 {chosen.map((i, index) => {
                let td = data[i] || '-';
                return <td key={index}>{td}</td>
            })}
            </tr>
        )
    }
}

        // {onCheck ? <td width={50} style={{ verticalAlign: "middle" }}>
        //         <input type="checkbox" disabled={checked.length === 1 && !isChecked && options.only} checked={isChecked} onChange={() => onCheck(isChecked ? _.without(checked, index) : _.union(checked, [index]))} />
        //     </td> : null}
        //     {chosen.map((i, index) => {
        //         let td = data[i] || '-';
        //         return <td key={index}>{td}</td>
        //     })}

class TFoot extends Component {
    goPrev() {
        let { options, skip, sendRequst } = this.props;
        const limit = options.limit;
        if (skip) {
            skip = skip - limit <= 0 ? 0 : skip - limit;
            sendRequst({
                skip: skip
            })
        }
    }
    goNext() {
        let { options, skip, count, sendRequst } = this.props;
        const limit = options.limit,
            maxPageCount = options.maxPageCount || 50;
        count = Math.min(count, maxPageCount * limit);

        if (skip + limit < count) {
            skip = skip + limit >= count ? count : skip + limit;
            sendRequst({
                skip: skip
            })
        }
    }
    pageTo(e) {
        const { options, skip, sendRequst } = this.props;
        const limit = options.limit,
            skipTo = parseInt(e.target.innerHTML - 1) * limit;
        if (skip != skipTo) {
            sendRequst({
                skip: skipTo
            })
        }
    }
    render() {
        const { options, chosen, data, skip, count } = this.props;
        const limit = options.limit,
            current = parseInt(skip / limit),
            maxPageCount = options.maxPageCount || 50,
            length = Math.min(Math.ceil(count / limit), maxPageCount);
        let start = 0,
            max = length,
            ulHtml = [],
            rangeHtml = ' 0 / 0';

        if (length > 9) {
            if (current - 4 >= 0 && current + 4 <= length - 1) {
                start = current - 4;
                max = current + 5
            } else if (current - 4 >= 0 && current + 4 > length - 1) {
                start = length - 9;
            } else if (current - 4 < 0 && current + 4 <= length - 1) {
                max = 9
            }
        }
        for (let i = start; i < max; i++) {
            let className = '';
            if (i == current) {
                className = 'active'
            }
            ulHtml.push(<li key={i} className={className} onClick={(e) => this.pageTo(e)}><a href="Javascript:void(0)">{i + 1}</a></li>)
        }

        if (count) {
            rangeHtml = ' ' + (skip + 1) + ' - ' + (skip + 1 + limit > count ? count : skip + limit) + ' / ' + count
        }

        return <div className="box-footer clearfix">
            <div className="pull-left text-muted" style={{ margin: '5px 0 0 5px' }}>{rangeHtml}</div>
            <ul className="pagination pagination-sm no-margin pull-right">
                <li onClick={() => this.goPrev()}><a href="Javascript:void(0)">«</a></li>
                {ulHtml}
                <li onClick={() => this.goNext()}><a href="Javascript:void(0)">»</a></li>
            </ul>
        </div>
    }
}

export class DownLoad extends Component {
    constructor() {
        super();
    }

    onSubmit() {
        document.getElementById(this.props.id).submit();
    }

    getSubmitValue() {
        const { getQuery, id } = this.props;
        return JSON.stringify(getQuery().query);
    }
    render() {
        const { downloadUrl, id } = this.props;
        const onSubmit = this.onSubmit.bind(this),
            getSubmitValue = this.getSubmitValue.bind(this);
        return <div className="btn-group pull-right">
            <div onClick={onSubmit}>
                <a type="button" className="btn btn-default btn-sm" title="下载CSV文件"><i className="fa fa-download text-muted"></i></a>
            </div>
            <form id={id} name={id} action={downloadUrl} target="_blank">
                <input type="hidden" name="data" value={getSubmitValue()} />
            </form>
        </div>
    }
}

export class SearchBar extends Component {
    constructor() {
        super();

        this.state = {
            value: '',
            theKey: '',
            time: ''
        }
    }
    componentDidMount() {
        const { theKey, time } = this.props;
        this.setState({
            theKey: theKey,
            time: time
        })
    }
    inputValue(e) {
        this.setState({
            value: e.target.value
        })
    }
    submit(e) {
        e.stopPropagation();
        e.preventDefault();

        const { val, onSubmit } = this.props;
        const theKey = this.state.theKey;

        if (val === this.state.value) {
            return
        }
        onSubmit({
            [theKey]: this.state.value
        })
    }
    handleUpdateTheKey(e) {
        this.setState({
            theKey: e.target.value
        })
    }
    handleUpdateTime(e) {
        this.setState({
            time: e.target.value
        })
    }
    render() {

        return
        <div className="box-tools box-tools-react pull-right">
            <form onSubmit={(e) => this.submit(e)}>
                <div className="input-group input-group-sm">
                    <input type="text" style={{ width: thead ? 127 : "" }} className="form-control" placeholder={placeholder || '请输入关键字'} value={value} onChange={(e) => this.inputValue(e)} />
                    <div className="input-group-btn">
                        <button type="submit" className="btn btn-default" title="搜索">
                            <i className="fa fa-search"></i>
                        </button>
                    </div>
                </div>
            </form>
        </div>
    }
} 